package com.example.aesdemo.controller;

import com.example.aesdemo.entity.RequestData;
import com.example.aesdemo.entity.ResultData;
import com.example.aesdemo.util.AesUtil;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @description: home
 * @author: Mr.Hu
 * @create: 2018-05-25 13:48
 **/
@Controller
@RequestMapping("/")
public class HomeController {

    @Autowired
    private AesUtil aesUtil;

    @GetMapping("index")
    public ModelAndView toIndex(){
        return new ModelAndView("index");
    }

    @GetMapping("encrypt")
    @ResponseBody
    public Map encrypt(String plaintext){
        Map map = Maps.newHashMap();
        String iv = AesUtil.random(16);
        String salt = AesUtil.random(16);
        String encrypt = aesUtil.encrypt(salt, iv, plaintext);
        map.put("iv",iv);
        map.put("salt",salt);
        map.put("encrypt",encrypt);
        return map;
    }

    @GetMapping("decrypt")
    @ResponseBody
    public Map decrypt(String ciphertext, String iv, String salt){
        String decrypt = aesUtil.decrypt(salt, iv, ciphertext);
        Map map = Maps.newHashMap();
        map.put("iv",iv);
        map.put("salt",salt);
        map.put("decrypt",decrypt);
        return map;
    }

    @PostMapping("postJson")
    @ResponseBody
    public ResultData postJson(RequestData data){
        return ResultData.success(data);
    }
}
